package com.taotao.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.taotao.common.pojo.EasyUIResult;
import com.taotao.search.pojo.Item;

@Service
public class SearchService {
	
	@Autowired
	private HttpSolrServer httpSolrServer;

	/**
	 * 根据条件分页搜索
	 * @param query
	 * @param pageNum
	 * @param rows
	 * @return
	 */
	public EasyUIResult<Item> search(String query, Integer pageNum, Integer rows) {
		
		try {
			// 高亮flag
			Boolean flag = true;
			// 判断条件是否为空
			if(StringUtils.isEmpty(query)){
				query = "*";
				flag = false;
			}
			
			// 创建查询对象
			SolrQuery solrQuery = new SolrQuery("title:" + query);
			
			// 设置分页参数
			solrQuery.setStart((pageNum-1)*rows);
			solrQuery.setRows(rows);
			
			// 设置高亮字段
			if(flag){
				solrQuery.setHighlight(true);
				solrQuery.addHighlightField("title");
				solrQuery.setHighlightSimplePre("<em>");
				solrQuery.setHighlightSimplePost("</em>");
			}
			
			// 执行查询操作
			QueryResponse response = this.httpSolrServer.query(solrQuery);
			
			// 解析结果集
			List<Item> itemList = response.getBeans(Item.class);
			
			// 如果没有高亮直接返回普通结果集
			if(!flag){
				return new EasyUIResult<>(response.getResults().getNumFound(), itemList);
			}
			
			// 如果要高亮
			Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
			for (Item item : itemList) {
				Map<String, List<String>> map = highlighting.get(item.getId().toString());
				if(!CollectionUtils.isEmpty(map) && !CollectionUtils.isEmpty(map.get("title"))){
					item.setTitle(map.get("title").get(0));
				}
			}
			
			return new EasyUIResult<>(response.getResults().getNumFound(), itemList);
		} catch (SolrServerException e) {
			e.printStackTrace();
		}
		return new EasyUIResult<>(0l, new ArrayList<Item>());
	}

}
